package io.github.uicdb.badskill.network;

import io.github.uicdb.badskill.OnlyCapabilityProvider;
import lombok.RequiredArgsConstructor;
import net.minecraft.client.Minecraft;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.network.NetworkEvent;

import java.util.List;
import java.util.function.Supplier;

@RequiredArgsConstructor
public class AllOnlySyncPackage {
    private final List<String> list;

    public static AllOnlySyncPackage create(List<String> list){
        return new AllOnlySyncPackage(list);
    }
    public  void toBytes(FriendlyByteBuf buf) {
        buf.writeCollection(list,FriendlyByteBuf::writeUtf);
    }

    public static AllOnlySyncPackage create(FriendlyByteBuf buf) {
        return new AllOnlySyncPackage(buf.readList(FriendlyByteBuf::readUtf));
    }

    public  void handle(Supplier<NetworkEvent.Context> contextSupplier) {
        var context=contextSupplier.get();
        context.enqueueWork(() -> {
            if(context.getDirection().getReceptionSide()== LogicalSide.CLIENT){
                Minecraft.getInstance().player.getCapability(OnlyCapabilityProvider.CAPABILITY)
                        .ifPresent(capability -> {
                            capability.getExistKeys().clear();
                            capability.getExistKeys().addAll(list);
                        });
            }});
        context.setPacketHandled(true);
    }
}
